package com.whc.service.impl;

import com.mongodb.client.result.UpdateResult;
import com.whc.entity.Message;
import com.whc.mapper.MessageMapper;
import com.whc.service.MessageService;
import com.whc.utils.SnowflakeIdGenerator;
import com.whc.vo.MessageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 韦红材
 * @ClassName MessageServiceImpl
 * @data 2024/12/10 17:01
 * @Version V1.0
 **/
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void add(Message message) {
        long id = snowflakeIdGenerator.generateId();
        message.setId(id);
        mongoTemplate.save(message);
    }


    @Override
    public List<MessageVo> getAll(long senderId,long accepterId) {
        Criteria condition1 = Criteria.where("senderId").is(senderId).and("accepterId").is(accepterId);
        Criteria condition2 = Criteria.where("senderId").is(accepterId).and("accepterId").is(senderId);
        Criteria finalCondition = new Criteria().orOperator(condition1, condition2);
        // 创建查询对象
        Query query = new Query(finalCondition);
        // 执行查询
        List<Message> messages = mongoTemplate.find(query, Message.class);

        ArrayList<MessageVo> messageVos = new ArrayList<>();
        for(Message m:messages){
            MessageVo messageVo = new MessageVo();
            BeanUtils.copyProperties(m,messageVo);
            messageVos.add(messageVo);
        }

        return messageVos;
    }

    @Override
    public void updateMessage(Message message) {
        Query query = Query.query(Criteria.where("_id").is(message.getId()));
        Update update = Update.update("type", 0);
        mongoTemplate.updateFirst(query, update, Message.class);

    }

    //todo 搞一个id的生成策略
    @Override
    public void deleteMessage(long id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,Message.class);
    }


}
